package com.busi.util;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.Properties;  
import java.util.UUID;  
import java.util.Vector;  

import org.apache.log4j.Logger;
  
import com.jcraft.jsch.Channel;  
import com.jcraft.jsch.ChannelSftp;  
import com.jcraft.jsch.JSch;  
import com.jcraft.jsch.Session;  
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;  

public class SFtpUtil {
	
	protected final static Logger LOG = Logger.getLogger(SFtp.class);
	//private static ChannelSftp sftp = null;  
    //账号  
   /* private static String user = PropertyUtil.getStrValue("mall.user", "");  
    //主机ip  
    private static String host =  PropertyUtil.getStrValue("mall.host", "");  
    //密码  
    private static String password = PropertyUtil.getStrValue("mall.password", "");  
    //端口  
*/    private static int port = 22;  
    /*//上传地址  
    private static String directory = PropertyUtil.getStrValue("mall.directory", "");  
    //下载目录  
    private static String saveFile = PropertyUtil.getStrValue("mall.saveFile", "");  
      */
    public static ChannelSftp getConnect(String user,String host,String password,String directory,String saveFile){  
    	ChannelSftp sftp = null;
        try {  
            JSch jsch = new JSch();  
  
            //获取sshSession  账号-ip-端口  
            Session sshSession =jsch.getSession(user, host,port);  
            //添加密码  
            sshSession.setPassword(password);  
            Properties sshConfig = new Properties();  
            //严格主机密钥检查  
            sshConfig.put("StrictHostKeyChecking", "no");  
              
            sshSession.setConfig(sshConfig);  
            //开启sshSession链接  
            sshSession.connect();  
            //获取sftp通道  
            Channel channel = sshSession.openChannel("sftp");  
            //开启  
            channel.connect();  
            sftp = (ChannelSftp) channel;  
        } catch (Exception e) {  
        	LOG.error("连接sftp异常", e);
        }  
        return sftp;  
    }  
    
    /**
    * 上传文件
    * @param directory 上传的目录
    * @param uploadFile 要上传的文件
    * @param sftp
    */
    public static boolean upload(String directory,String uploadFile, ChannelSftp sftp,String filename) {
	    boolean result = false;  
	    try {
	    	try{
			    sftp.cd(directory);
	    	}catch(SftpException sException){
			    if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
			    	 sftp.mkdir(directory);
			         sftp.cd(directory);
			    }
	    	}	
		    File file=new File(uploadFile);
		    sftp.put(new FileInputStream(file), filename);
		    result = true;
	    } catch (Exception e) {
	    	LOG.error("上传文件异常", e);
	    }
	    return result;
    }
      
   /* *//** 
     *  
     * @param uploadFile 上传文件的路径 
     * @return 服务器上文件名 
     *//*  
    public String upload(String uploadFile,String directory,ChannelSftp sftp) {  
        File file = null;  
        String fileName = null;  
        try {  
            sftp.cd(directory);  
            file = new File(uploadFile);  
            //获取随机文件名  
            fileName  = UUID.randomUUID().toString() + file.getName().substring(file.getName().length()-5);  
            //文件名是 随机数加文件名的后5位  
            sftp.put(new FileInputStream(file), fileName);  
        } catch (Exception e) {  
        	LOG.error("上传文件异常", e);
        }  
        return file == null ? null : fileName;  
    }  */
      
    /** 
     * 下载文件 
     *  
     * @param directory 
     *            下载目录 
     * @param downloadFile 
     *            下载的文件名 
     * @param saveFile 
     *            存在本地的路径 
     * @param sftp 
     */  
    public static boolean download(String downloadFileName,String directory,String saveFile,ChannelSftp sftp) {  
    	boolean result = false;  
        try {  
            sftp.cd(directory);  
              
            File file = new File(saveFile);  
              
            sftp.get(downloadFileName, new FileOutputStream(file));  
            result = true;
        } catch (Exception e) {  
        	LOG.error("下载文件异常", e);
        }  
        return result;
    }  
      
    /** 
     * 删除文件 
     *  
     * @param deleteFile 
     *            要删除的文件名字 
     * @param sftp 
     */  
    public static void delete(String directory,String deleteFile, ChannelSftp sftp) {  
        try {  
            sftp.cd(directory);  
            sftp.rm(deleteFile);  
        } catch (Exception e) {  
        	LOG.error("删除文件异常", e);
        }  
    }  
      
    /** 
     * 列出目录下的文件 
     *  
     * @param directory 
     *            要列出的目录 
     * @param sftp 
     * @return 
     * @throws SftpException 
     */  
    public Vector listFiles(String directory, ChannelSftp sftp)  
            throws SftpException {  
        return sftp.ls(directory);  
    }  
    /**
	 * 判断远程文件是否存在
	 * @author inber
	 * @since 2012.02.09
	 * @param srcSftpFilePath
	 * @return
	 * @throws SftpException
	 */
	public static boolean  isFileExist (String srcSftpFilePath,ChannelSftp sftp) throws SftpException {
		boolean isExitFlag = false;
		// 文件大于等于0则存在文件
		if (getFileSize(srcSftpFilePath,sftp) >= 0) {
			isExitFlag = true;
		}
		return isExitFlag;
	}
	/** 得到远程文件大小
	 * @author inber
	 * @since 2012.02.09
	 * @see   返回文件大小
	 * @param srcSftpFilePath
	 * @return 返回文件大小，如返回-2 文件不存在，-1文件读取异常
	 * @throws SftpException
	 */
	public static long getFileSize (String srcSftpFilePath,ChannelSftp sftp) throws SftpException {
		long filesize = 0;//文件大于等于0则存在
		try {
			SftpATTRS sftpATTRS = sftp.lstat(srcSftpFilePath);
			filesize = sftpATTRS.getSize();
		} catch (Exception e) {
			filesize = -1;//获取文件大小异常
			if (e.getMessage().toLowerCase().equals("no such file")) {
				filesize = -2;//文件不存在
			}
		}
		return filesize;
	}
}
